package view;

import dao.Blog;
import dao.BlogDao;
import dao.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/delete")
public class Delete extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getSession(false) == null){
            resp.sendRedirect("login.html");
            return;
        }
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        HttpSession httpSession = req.getSession();
        User user = (User) httpSession.getAttribute("user");
        String blogId = req.getParameter("blogId");
        BlogDao blogDao = new BlogDao();
        try {
            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            if (blog.getUserId() == user.getUserId()){
                blogDao.delete(Integer.parseInt(blogId));
                System.out.println("删除成功");
                resp.sendRedirect("blogList.html");
            }else {
                resp.getWriter().write("<h3> 不能删除他人文章 </h3>");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
